package com.tqjc.system.core.task;

import com.tqjc.system.common.constant.ConfigConstant;
import com.tqjc.system.core.gate.constants.GateConstant;
import com.tqjc.system.core.util.FileUtils;
import com.tqjc.system.system.entity.SysConfigEntity;
import com.tqjc.system.system.service.SysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 86195
 * @version 1.0
 * @description 车牌相片管理任务
 * @date 2023/9/21 14:15
 */
@Component
@Slf4j
public class CarPhotoManageTask {

    @Autowired
    private SysConfigService configService;


    /**
     * 每天执行一次，删除90-120天之间的照片
     *
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void delPhoto(){

        //获取配置的摄像头IP地址
        List<SysConfigEntity> ips = configService.getConfigInfoByType(ConfigConstant.CONFIG_TYPE_CAMERA_GATENAME_IP);
        //获取删除日期配置
        SysConfigEntity delConfig = configService.getConfigInfo(ConfigConstant.CONFIG_TYPE_SCHEDULED_TASK_INFO, ConfigConstant.CONFIG_ID_CAR_PHOTO_DEL);
        String[] split = delConfig.getConfigValue().split("-");

        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 计算配置T1天前的日期  最早的时间
        LocalDateTime earliestDate = now.minusDays(Integer.valueOf(split[1]));
        //计算配置T2前的日期   最晚时间
        LocalDateTime latestDate  = now.minusDays(Integer.valueOf(split[0]));
        // 生成日期列表
        List<LocalDateTime> dateList = new ArrayList<>();
        for (LocalDateTime date = earliestDate; date.isBefore(latestDate); date = date.plusDays(1)) {
            dateList.add(date);
        }

        ips.forEach(e ->{
            //每一个IP文件进行删除
            String pathPrefix = GateConstant.FILE_PREFIX + e.getConfigId();
            dateList.forEach( date -> {
                String filePath = FileUtils.getFilePath(pathPrefix, date);
                File file = new File(filePath);
                if(file.exists()){
                    File[] files = file.listFiles();
                    for (File f : files) {
                        f.delete();
                    }
                }
            });
        });

    }
}
